package com.wrx.Controller.controllers;


import com.wrx.Controller.Result.Code;
import com.wrx.Controller.Result.Result;
import com.wrx.pojo.Book;
import com.wrx.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {
    @Autowired
    private BookService bookService;
    /**
     * 保存
     * @return
     */
    @PostMapping
    public Result save(@RequestBody Book book){
//        int i = 1/0;
        System.out.println(book);
        boolean save = bookService.save(book);
        Integer code  = save ? Code.SAVE_OK : Code.SAVE_ERR;
        return new Result(code,save);
    }

    /**
     * 删除
     * @return
     */
    @DeleteMapping("{id}")
    public Result delete(@PathVariable Integer id){
        boolean delete = bookService.delete(id);
        Integer code  = delete ? Code.DELETE_OK : Code.DELETE_ERR;
        return new Result(code,delete);
    }

    /**
     * 修改
     * @return
     */
    @PutMapping
    public Result update(@RequestBody Book book){
        boolean update = bookService.update(book);
        Integer code  = update ? Code.UPDATE_OK:Code.UPDATE_ERR;
        return new Result(code,update);

    }
    /**
     * 查询单个
     * @return
     */
@GetMapping("{id}")
    public Result getById(@PathVariable Integer id){
        Book byId = bookService.getById(id);
        Integer code = byId != null ? Code.GET_OK:Code.GET_ERR;
        String msg = byId != null ? "查询成功":"查询失败，请重试";
        return new Result(code,byId,msg);
    }
    /**
     * 查询所有
     * @return
     */
    @GetMapping
    public Result getAll(){
        List<Book> all = bookService.getAll();
        Integer code = all!= null ? Code.GET_ALL_OK:Code.GET_ALL_ERR;
        String msg = all != null ? "查询成功":"查询失败，请重试";
        return new Result(code,all,msg);
    }


}
